package control;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import remote.GestioneUtentiRemote;

public class GestioneUtentiServlet extends Servlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String to = (String) request.getParameter("to");
		if (to.equals("redirectToPaginaProfilo"))
			this.redirectToPaginaProfilo(request, response);
		if (to.equals("getFotoProfilo"))
			this.getFotoProfilo(request, response);
	}

	// da utente/. a utente/profilo.jsp
	private void redirectToPaginaProfilo(HttpServletRequest request,
			HttpServletResponse response) {
		redirect("utente/profilo.jsp", request, response);
	}

	private void getFotoProfilo(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Context jndiContext = new javax.naming.InitialContext();
			Object ref2 = jndiContext.lookup("GestioneUtenti/remote");
			GestioneUtentiRemote gestioneUtentiRemote = (GestioneUtentiRemote) PortableRemoteObject
					.narrow(ref2, GestioneUtentiRemote.class);

			String username = request.getParameter("username");

			byte[] fotoProfilo = gestioneUtentiRemote.getFotoProfilo(username);

			response.setContentType("image/png");
			response.setContentLength(fotoProfilo.length);
			response.getOutputStream().write(fotoProfilo);
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
